// src/utils/event.ts

type Callback = (...args: any[]) => void;

class EventEmitter {
  private events: Record<string, Callback[]> = {};

  // 订阅事件
  public on(key: string, callback: Callback): () => void {
    if (!this.events[key]) {
      this.events[key] = [];
    }
    this.events[key].push(callback);

    // 返回一个取消订阅的函数，这非常重要！
    return () => {
      this.off(key, callback);
    };
  }

  // 取消订阅
  public off(key: string, callback: Callback): void {
    const callbacks = this.events[key];
    if (callbacks) {
      this.events[key] = callbacks.filter(cb => cb !== callback);
    }
  }

  // 触发事件
  public trigger(key: string, ...args: any[]): void {
    const callbacks = this.events[key];
    if (callbacks) {
      callbacks.forEach(cb => {
        try {
          cb(...args);
        } catch (error) {
          console.error(`Error in event listener for ${key}:`, error);
        }
      });
    }
  }
}

// 创建一个单例，供整个应用使用
const eventBus = new EventEmitter();

// 为了和你的代码保持一致，我们可以封装成一个静态类
export default class EventUtils {
  // 定义事件名称常量
  static readonly UserInfo = 'refreshUserinfo';
  static readonly ApplyRecharge = 'applyRecharge';
  static readonly RefreshOrder = 'RefreshOrder';
  // ... 其他事件

  static on(key: string, callback: Callback) {
    return eventBus.on(key, callback);
  }

  static trigger(key: string, data?: any) {
    eventBus.trigger(key, data);
  }
}
